package ch.fhnw.qualiscan.cron;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.models.SurveyModel;
import ch.fhnw.qualiscan.core.db.pojos.Survey;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.db.pojos.User;
import ch.fhnw.qualiscan.core.helpers.EmailHelper;

public class CronJob extends HttpServlet {
	
	public SurveyModel surveyModel;
	public Config config;
	public EmailHelper emailHelper;
	
	public CronJob() {
		config = new Config();
		surveyModel = new SurveyModel();
		emailHelper = new EmailHelper();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 
		
		if (request.getParameter("do").equals("coordinatorreminder")) {
			sendCoordinatorReminders();
		}
		
	}
	
	/**
	 * Sends a email to the coordinator of a survey, one day before the surveys deadline.
	 */
	public void sendCoordinatorReminders() {
		
		Date dateNow = new Date();
		List<Survey> sendMailSurveyList = new ArrayList<Survey>();
		List<Survey> surveyList = surveyModel.getAllSurveys();
		
		/*
		 * Select Surveys, where the coordinator needs to be informed about the deadline.
		 */
		for (int i = 0; i < surveyList.size(); i++) {
			if (surveyList.get(i).getStage().getId() == config.STAGE_SURVEY) {
				if (dateNow.compareTo(surveyList.get(i).getCompletiondate()) < 0) {
					long diff = surveyList.get(i).getCompletiondate().getTime() - dateNow.getTime();
					long diffDay = diff /(1000 * 60 * 60 * 24);
					if (diffDay <= 1) {
						sendMailSurveyList.add(surveyList.get(i));
					}
				}
			}
		}
		
		/*
		 * Get the coordinators email address and send emails
		 */
		for(int a = 0; a < sendMailSurveyList.size(); a++) {
			List<SurveyUserRole> coordinatorList = surveyModel.getCoordinatorsOfSurvey(sendMailSurveyList.get(a));
			for(int j = 0; j < coordinatorList.size(); j++) {
				emailHelper.sendCoordinatorReminderEmail(coordinatorList.get(j).getUser(), sendMailSurveyList.get(a));
			}
		}
	}
}
